package com.mobicartel.androidto;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class DashboardActivity extends Activity implements OnFocusChangeListener, OnItemClickListener, OnClickListener {
	
	public static final int Menu1 = Menu.FIRST + 1;
	public static final int Menu2 = Menu.FIRST + 2;
	// Create context menu
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Menu1, 0, "Website").setIcon(R.drawable.ic_menu_compass);
		menu.add(0, Menu2, 0, "Settings");
	    return true;
	}
	// Listener for context menu options
	public boolean onOptionsItemSelected(MenuItem item) {
		  switch (item.getItemId()) {
		    case Menu1:
		    	Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.androidto.com"));
		    	startActivity(webIntent); 
		    	break;
		    case Menu2:
		    	break;
		  }
		  return false;
	}
	
	// Declare XML widgets
	private TextView txt_marquee_alerts;
	private ListView listview_twitter;
	private Button btn_tweet;
	private ProgressBar progress_tweets;
	public final long CONFERENCE_START_MILLIS = parseTime(
    	"2010-10-26T08:30:00.000-04:00");
	public final long CONFERENCE_END_MILLIS = parseTime(
    	"2010-10-26T17:00:00.000-04:00");
	private static Time sTime = new Time();
	private Handler mMessageHandler = new Handler();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        
        mMessageHandler.post(mCountdownRunnable);
        // Attach widgets to XML by ID and set listeners
        txt_marquee_alerts = (TextView) findViewById(R.id.txt_marquee_alerts);
        txt_marquee_alerts.requestFocus();
        listview_twitter = (ListView) findViewById(R.id.listview_twitter);
        listview_twitter.setOnItemClickListener(this);
        btn_tweet = (Button) findViewById(R.id.btn_tweet);
        btn_tweet.setOnClickListener(this);
        progress_tweets = (ProgressBar) findViewById(R.id.progress_tweets);
        
        // Check for network connectivity before performing a network operation. 
    	// If you don't do this then bad things will happen, really bad things...
    	ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
		if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED  ) {
			// Display an indeterminate progress bar and execute the ASync thread to 
			// download the tweets that say "androidto" in them.
			progress_tweets.setVisibility(ProgressBar.VISIBLE);
			new DownloadTweets().execute("androidto");
		} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED   ) {
			Toast.makeText(this, "No Connection", Toast.LENGTH_SHORT).show();
		} 
        
    }
    
    @Override
    public void onStart() {
    	super.onStart();
		
		
    	
    }
    
    @Override
	public void onFocusChange(View view, boolean hasFocus) {

    	// Keep marquee focused so that it continues to scroll
    	txt_marquee_alerts.requestFocus();
		
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		
		// This code is executed when an item in a list is clicked.
		switch(view.getId()) {
		case(R.id.listview_twitter):
			
			break;
		}
		
	}

	@Override
	public void onClick(View view) {
		
		// This code is executed when the user clicks a button
		switch(view.getId()) {
		case(R.id.btn_tweet):
			// This intent generates a list of applications able to handle the ACTION_SEND intent.
			// It also feeds the AndroidTO hashtag to the receiving application
			Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
			shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "#AndroidTO");
			shareIntent.setType("text/plain");
			startActivity(Intent.createChooser(shareIntent, "Tweet about AndroidTO"));
			break;
		}
		
	}
	
	// Use ASync Threading for long operations like this
	private class DownloadTweets extends AsyncTask<String, Integer, List<String>> {

		@Override
		protected List<String> doInBackground(String... query) {
			
			// Create two list arrays, one for the Tweet Objects, and one for the String representations
			List<Tweet> list_tweets = new ArrayList<Tweet>();
			List<String> list_str_tweets = new ArrayList<String>();
			
			try {
				// Create an instance of Twitter
	    		TwitterFactory factory = new TwitterFactory(TwitterConfig.getTwitterConfiguration());
	        	Twitter twitter = factory.getInstance();
	        	
	        	// Create a Query object to search for on Twitter
	        	Query search_query = new Query(query[0]);
				QueryResult search_result = twitter.search(search_query);
				
				list_tweets = search_result.getTweets();
				
				// Use a "for each" statement to create a list of tweets in string form
				for (Tweet tweet : list_tweets) {
					list_str_tweets.add(tweet.getFromUser() + "\n--" + tweet.getText());
				}
				
			} catch (TwitterException e) {
				// Oh no! Something has gone wrong!
				// If you wanted you could find the error code from the exception
				// and use it to find out the issue and then notify the user.
				e.printStackTrace();
			}
			
			
			return list_str_tweets;
		}
		
		@Override
	    protected void onPostExecute(List<String> result) {
			
			// Get rid of the indeterminate progress bar and display the search results
			progress_tweets.setVisibility(ProgressBar.INVISIBLE);
			DisplayTweets(result);
			
	    }

	}
	
	private void DisplayTweets(List<String> list_str_tweets) {
		
		// Create an ArrayAdapter for the ListView with the tweets
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, R.id.label, list_str_tweets);
		listview_twitter.setAdapter(adapter);
		
	}
	
	public long parseTime(String time) {
        sTime.parse3339(time);
        return sTime.toMillis(false);
    }
	
	private Runnable mCountdownRunnable = new Runnable() {

		@Override
		public void run() {
			
			// Get todays date and create a Calendar object for the countdown expiry
			Calendar rightNow = Calendar.getInstance();
	        Calendar expireDate = new GregorianCalendar(2011,Calendar.OCTOBER, 26);

	        // Check to see if there is still time left until October 26th
	        if (rightNow.before(expireDate)) {
	        	
	        	int remainingSec = (int) Math.max(0,
	        			(CONFERENCE_START_MILLIS - System.currentTimeMillis()) / 1000);
	        	final boolean conferenceStarted = remainingSec == 0;
	        	if (conferenceStarted) {
	        		txt_marquee_alerts.setText("Started already???");
	        		mMessageHandler.postDelayed(new Runnable() {
	        			public void run() {
	        				reloadNowPlaying(true);
             	       }
	        		}, 100);
	        		return;
	        	}
            
	        	final int secs = remainingSec % 86400;
	        	final int days = remainingSec / 86400;
	        	final String str = getResources().getQuantityString(
	        		R.plurals.now_playing_countdown, days, days,
	        		DateUtils.formatElapsedTime(secs));
	        	txt_marquee_alerts.setText(str + " until AndroidTO!");

	        	// Repost ourselves to keep updating countdown
	        	mMessageHandler.postDelayed(mCountdownRunnable, 1000);
	        } else {
	        	
	        	getAlerts("http://androidguys.savina.net/androidto_alerts.txt");
	        	
	        }
		}
		
		
	};
	
	private void getAlerts(String url) {
		
		new DownloadAlerts().execute(url);
		
	}
	
	private class DownloadAlerts extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... url) {
			
			String str_alerts = "";
			
			URL alerts_url;
			try {
				alerts_url = new URL(url[0]);
				BufferedReader br = new BufferedReader(new InputStreamReader(alerts_url.openStream()));
				str_alerts = br.readLine();
				br.close();
			} catch (MalformedURLException e) {
				Log.e("AndroidTO Alerts", e.toString());
			} catch (IOException e) {
				Log.e("AndroidTO Alerts", e.toString());
			}
       	
			
			return str_alerts;
		}
		
		@Override
	    protected void onPostExecute(String result) {
			txt_marquee_alerts.setText(result.toString());
	    }

	}
	
	private void reloadNowPlaying(boolean forceRelocate) {
		
	}
}
